package com.mh.system.service.impl;

import com.mh.common.core.exception.BaseException;
import com.mh.common.enums.SysUserStatus;
import com.mh.framework.service.SysPermsService;
import com.mh.system.domain.LoginUserDetails;
import com.mh.system.domain.SysUser;
import com.mh.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

//处理用户验证
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysPermsService permsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userService.selectByUserName(username);

        //查询结果为空 = 用户不存在
        if (user == null) {
            log.info("登录用户:{} 不存在",username);
            throw new UsernameNotFoundException(username);
        }
        //自定义枚举类中获取删除的code 与 查询结果中的delFlag字段 比较 --> 一样true = 被删除账号
        else if (SysUserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户:{} 已被删除",username);
            throw new BaseException("您的账号:"+username+"已被删除");
        }
        //自定义枚举类中获取停用的code 与 查询结果中的status字段 比较 --> 一样true = 被停用账号
        else if (SysUserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户:{} 已被停用",username);
            throw new BaseException("您的账号:"+username+"已被停用");
        }

        //调用之前写过的获取权限信息的service, 获取该用户权限
        Set<String> perms = permsService.getPerms(user);

        //传入user对象&权限(LoginUserDetails有对应构造器)
        return new LoginUserDetails(user,perms);
    }
}
